<template>
  <el-dialog :title="dialogData.title"
             :close-on-click-modal='false'
             :visible.sync="dialogData.show"
             center
             width="90%"
             @close="$emit('closedialog')">
    <el-form :model="formdata"
             label-position="right"
             label-width="140px"
             :rules="formRules"
             ref="formRefs">
      <el-form-item label="服务包名称："
                    prop="name">
        <el-input v-model="formdata.name"
                  maxlength="20"
                  autocomplete="off"
                  placeholder="请输入服务包名称"
                  class="w-200"></el-input>
      </el-form-item>
      <el-form-item label="所属医院："
                    prop="hospitalId">
        <el-select v-model="formdata.hospitalId"
                   filterable
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'hospital')}"
                   placeholder="请输入医院名称"
                   class="w-200"
                   :loading="loading1"
                   @change="val=>changeHospital(val, 'hospital')">
          <el-option v-for="option in hospitalList"
                     :value="option.id"
                     :label="option.name"
                     :key="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="带队专家："
                    prop="leaderId">
        <el-select v-model="formdata.leaderId"
                   @change="changeLeader"
                   clearable
                   filterable
                   class="w-200"
                   placeholder="请选择带队专家">
          <el-option v-for="option in doctorLeaders"
                     :value="option.id"
                     :key="option.id"
                     :label="option.nickName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作室："
                    prop="studioId">
        <el-select v-model="formdata.studioId"
                   @change="changeStudio"
                   clearable
                   placeholder="请选择工作室">
          <el-option v-for="item in studioIdlist"
                     :key="item.id"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="团队成员："
                    v-if="formdata.studioId">
        <div v-if="formdata.doctorList.length"
             style="display:flex;text-align:center;flex-wrap:wrap">
          <div v-for="(it,index) in formdata.doctorList"
               :key='index'
               style="margin-left:5px">
            <img :src="it.headImageUrl"
                 style="height:100px;width:100px">
            <div style="font-size:12px">{{it.nickName}} <span style="padding-left:5px"></span> {{it.isExpert == 0?'普通成员':it.isExpert == 1?'三甲专家':'专科专家'}}</div>
          </div>
        </div>
        <div v-else>
          没有成员
        </div>
      </el-form-item>
      <el-form-item label="服务价格："
                    prop="price">
        <el-input-number :min="0"
                         :precision="2"
                         :controls="false"
                         v-model="formdata.price"
                         type="number"
                         placeholder="单位（元）"
                         class="w-200"></el-input-number>
      </el-form-item>
      <el-form-item label="服务有效期(月)："
                    prop="totalMonth">
        <el-input-number :min="0"
                         :precision="0"
                         :controls="false"
                         v-model="formdata.totalMonth"
                         type="number"
                         placeholder="单位（月）"
                         class="w-200"></el-input-number>
      </el-form-item>
      <h3>服务包内容配置：</h3>
      <el-form-item label="服务内容说明："
                    prop="itemList">
        <el-button type="success"
                   @click="handleAdd">新 增 一 行</el-button>
        <el-table :data="formdata.itemList"
                  class="mt-20"
                  border>
          <el-table-column prop="serviceContent"
                           label="服务内容">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.serviceContent"
                            :prop="`itemList.${scope.$index}.serviceContent`">
                <el-input v-model="scope.row.serviceContent"
                          clearable
                          class="w-200"
                          placeholder="请输入服务内容"
                          maxlength="50"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="服务方式">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.hospitalPackageTypeId"
                            :prop="`itemList.${scope.$index}.hospitalPackageTypeId`">
                <el-select v-model="scope.row.hospitalPackageTypeId"
                           clearable
                           class="w-200"
                           placeholder="请选择服务方式">
                  <el-option v-for="item in serviceList"
                             :key="item.id"
                             :label="item.name"
                             :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="服务频次">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.serviceCount"
                            :prop="`itemList.${scope.$index}.serviceCount`">
                <el-input v-model="scope.row.serviceCount"
                          placeholder="请输入服务频次"
                          clearable
                          class="w-200"
                          @input="(val)=>{scope.row.serviceCount = val.replace(/[^\d]/g, '')}"
                          maxlength="8"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="说明">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.introduce"
                            :prop="`itemList.${scope.$index}.introduce`">
                <el-input v-model="scope.row.introduce"
                          clearable
                          type="textarea"
                          placeholder="请输入说明"
                          maxlength="250"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="服务延期单位">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.extensionType"
                            :prop="`itemList.${scope.$index}.extensionType`">
                <el-select v-model="scope.row.extensionType"
                           clearable
                           class="w-200"
                           placeholder="请选择服务延期单位">
                  <el-option label="日"
                             :value="1"></el-option>
                  <el-option label="月"
                             :value="2"></el-option>
                  <el-option label="年"
                             :value="3"></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="服务延期时间">
            <template slot-scope="scope">
              <el-form-item :rules="listRules.extension"
                            :prop="`itemList.${scope.$index}.extension`">
                <el-input v-model="scope.row.extension"
                          clearable
                          class="w-200"
                          placeholder="请输入服务延期时间"
                          @input="(val)=>{scope.row.extension = val.replace(/[^\d]/g, '')}"
                          maxlength="8"></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="删 除"
                           width="100"
                           align="center">
            <template slot-scope="scope">
              <el-button @click="delTable(formdata.itemList, scope.$index)"
                         type="danger">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <span style="font-size:12px">注：服务频次0表示不限次数, 其他数字为具体服务次数</span>
      </el-form-item>
      <el-form-item v-for="(item, index) in formdata.appreciationList"
                    :key="(index+1)*9"
                    :label="`${item.name}价格：`">
        <el-input-number :min="0"
                         :precision="2"
                         :controls="false"
                         v-model="item.price"
                         type="number"
                         :placeholder="`请输入${item.name}价格`"
                         class="w-200"></el-input-number>
      </el-form-item>
      <h3 v-if="formdata.hospitalId">赠送：</h3>
      <el-form-item v-for="(item, index) in formdata.giveawayList"
                    :key="(index+1)*8"
                    :label="`${item.name}数量：`">
        <el-input v-model="item.count"
                  maxlength="8"
                  @input="(val)=>{item.count = val.replace(/[^\d]/g, '')}"
                  autocomplete="off"
                  :placeholder="`请输入${item.name}数量`"
                  class="w-200"></el-input>
      </el-form-item>
      <el-form-item label="服务药店："
                    prop="pharmacyList">
        <el-select v-model="formdata.pharmacyList"
                   filterable
                   multiple
                   remote
                   reserve-keyword
                   clearable
                   :remote-method="(query) => {remoteMethod(query, 'pharmacy')}"
                   class="w-200"
                   :loading="loading"
                   placeholder="请输入药店名称"
                   @change="val=>handleSelect(val, 'pharmacy')">
          <el-option v-for="option in pharmacyListData"
                     :value="option.id"
                     :label="option.name"
                     :key="option.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="每单推广费用：">
        <el-input v-model="formdata.extendFee"
                  maxlength="8"
                  type="number"
                  autocomplete="off"
                  placeholder="请输入推广费用"
                  clearable
                  class="w-200"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="$emit('closedialog')">取 消</el-button>
      <el-button type="success"
                 @click="submitForm">确 认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  export default {
    props: ['dialogData'],
    data () {
      return {
        loading: false,
        loading1: false,
        formdata: {
          name: '',
          hospitalId: '', // 所属医院
          leaderId: '', // 带队专家
          studioId: '', // 工作室
          price: '', // 服务价格
          totalMonth: '', // 服务有效期
          itemList: [], // 服务包内容
          pharmacyList: [], // 服务药店
          extendFee: '', // 每单推广费用
          doctorList: [], // 团队成员
          appreciationList: [],
          giveawayList: [],
        },
        hospitalAllList: [], // 所属医院列表
        hospitalList: [],
        studioIdlist: [],
        doctorLeaders: [], // 带队专家列表
        serviceList: [], // 服务方式列表
        pharmacyListData: [], // 服务药店列表
        pharmacyAllLists: [], // 服务药店列表
        formRules: {
          name: [{ required: true, message: '请输入服务包名称', trigger: 'blur' }],
          hospitalId: [{ required: true, message: '请输入所属医院', trigger: ['blur', 'change'] }],
          leaderId: [{ required: true, message: '请选择带队专家', trigger: 'change' }],
          studioId: [{ required: true, message: '请选择医生工作室', trigger: 'blur' }],
          price: [{ required: true, message: '请输入随访包价格', trigger: 'blur' }],
          totalMonth: [{ required: true, message: '请输入服务包有效期', trigger: 'blur' }],
          pharmacyList: [{ required: true, message: '请输入合作药店', trigger: 'blur' }],
          itemList: [{ required: true, message: '请配置服务包内容', trigger: 'blur' }],
        },
        listRules: {
          serviceContent: [{ required: true, message: '请输入服务内容', trigger: 'blur' }],
          hospitalPackageTypeId: [{ required: true, message: '请选择服务方式', trigger: 'change' }],
          serviceCount: [{ required: true, message: '请输入服务内容', trigger: 'blur' }],
          introduce: [{ required: true, message: '请输入说明', trigger: 'blur' }],
          extensionType: [{ required: true, message: '请选择服务延期单位', trigger: 'change' }],
          extension: [{ required: true, message: '请输入服务延期时间', trigger: 'blur' }],
        }
      }
    },
    methods: {
      submitForm () {
        this.$refs.formRefs.validate((valid) => {
          if (valid) {
            if (!this.formdata.doctorList.length) {
              this.$message.warning('团队成员不能为空')
              return
            } else {
              /* for (let index = 0; index < this.formdata.doctorList.length; index++) {
                const element = this.formdata.doctorList[index];
                if (element.roleType != 1) {
                  this.$message.warning('请先添加管家角色')
                  return
                }
              } */
            }


            for (let index = 0; index < this.formdata.itemList.length; index++) {
              const element = this.formdata.itemList[index];

              if (element.serviceCount === 0) {
                element.serviceCount = String(element.serviceCount)
              }
              if (!element.serviceCount) {
                this.$message.warning('请填写正整数服务频次')
                return
              }

            }
            for (let index = 0; index < this.formdata.appreciationList.length; index++) {
              const element = this.formdata.appreciationList[index];
              if (!element.price || Number(element.price) == 0) {
                this.$message.warning('陪检券价格大于0且至多两位小数')
                return
              }
            }

            if (this.formdata.extendFee == 0) {
              this.formdata.extendFee = undefined
            }
            if (this.formdata.extendFee <= 0) {
              this.$message.warning('每单推广费用大于0且至多两位小数')
              return
            }
            if (this.formdata.extendFee >= this.formdata.price) {
              this.$message.warning('推广费用必须低于服务价格')
              return
            }
            if (this.formdata.extendFee) {
              this.formdata.way = 1;
            } else {
              this.formdata.way = null;
            }
            const cloneData = JSON.parse(JSON.stringify(this.formdata));

            let arr = [];
            cloneData.pharmacyList.forEach(item => {
              arr.push({
                hospitalId: item
              });
            })
            cloneData.pharmacyList = arr;
            // return
            this.post(this.api.cooperationHospital.hospitalPackageuploadInfo, cloneData).then((res) => {
              if (res.data.code === '200') {
                this.$message.success('保存成功!');
                this.$emit('closedialog');
              }
            });
          }
        })
      },
      // 服务包内容配置
      handleAdd () {
        this.formdata.itemList.push({
          serviceContent: '', // 服务内容
          hospitalPackageTypeId: '', // 服务方式
          serviceCount: '', // 服务频次
          introduce: '', // 说明
          extensionType: '', // 服务延期单位
          extension: '', // 服务延期时间
        });
      },
      delTable (table, index) {
        table.splice(index, 1);
      },

      // 选择所属医院
      changeHospital (val) {
        this.formdata.leaderId = '';
        this.formdata.studioId = '';
        this.studioIdlist = [];
        if (val) {
          this.doctorLeader(val);
          this.getPackageTypeList(val);
          this.getAppreciationList(val);
        } else {
          this.$message.error('请输入医院名称');
          this.doctorLeaders = [];
        }
      },
      // 获取带队专家
      doctorLeader (val) {
        this.post(this.api.cooperationHospital.getHospitalDoctor, {
          "pageSize": 100,
          "pageStart": 0,
          "hospitalId": val
        }).then((res) => {
          if (res.data.code === '200') {
            this.doctorLeaders = res.data.object;
          }
        });
      },
      // 选择带队专家
      changeLeader (val) {
        if (!this.formdata.studioId) {
          this.getDoctorStudio(val);
        } else {
          this.studioIdlist = [];
          this.formdata.studioId = '';
        }
      },
      //带队医生的工作室
      getDoctorStudio (val) {
        this.post(this.api.cooperationHospital.getDoctorStudio, { "pageSize": 100, "pageStart": 0, "doctorId": val }).then((res) => {
          if (res.data.code === '200') {
            this.studioIdlist = res.data.object;
          }
        });
      },
      // 选择工作室
      changeStudio (val) {
        if (val) {
          this.formdata.doctorList = this.studioIdlist.filter(ele => ele.id == val)[0].doctorDtos
          this.formdata.doctorList.forEach(ele => {
            ele.doctorId = ele.id;
            ele.roleType = 0;
          })
        }
      },
      // 服务方式列表
      getPackageTypeList (val) {
        this.post(this.api.cooperationHospital.getPackageTypeList, {
          "pageSize": 100,
          "pageStart": 0,
          "hospitalId": val
        }).then((res) => {
          if (res.data.code === '200') {
            this.serviceList = res.data.object;
          }
        });
      },
      // 陪诊劵
      getAppreciationList (hospitalId) {
        this.post(this.api.cooperationHospital.getAppreciationList, {
          "pageSize": 100,
          "pageStart": 0,
          "hospitalId": hospitalId
        }).then((res) => {
          if (res.data.code === '200') {
            let resData = res.data.object;
            this.formdata.appreciationList = resData.map(item => ({
              name: item.name, type: item.type, price: item.price
            }));
            this.formdata.giveawayList = resData.map(item => ({
              name: item.name, type: item.type, count: item.count
            }));
          }
        });
      },
      // 获取药店 远程搜索
      remoteMethod (query, type) {
        if (query !== '') {
          let _this = this;
          if (query) {
            if (type === 'pharmacy') {
              _this.loading = true; // 锁住
              this.post(this.api.hospitalManager.list, {
                "pageSize": 100,
                "pageStart": 0,
                "name": query
              }).then((res) => {
                if (res.data.code === '200') {
                  this.pharmacyAllLists = res.data.object;
                }
              });
              setTimeout(() => {
                _this.loading = false;
                _this.pharmacyListData = _this.pharmacyAllLists.filter(item => item.name.indexOf(query) > -1);
                console.log(this.pharmacyListData)
              }, 200);
            }
            // 获取医院
            if (type === 'hospital') {
              _this.loading1 = true; // 锁住
              this.post(this.api.hospitalManager.list, {
                "pageSize": 100,
                "pageStart": 0,
                "name": query
              }).then((res) => {
                if (res.data.code === '200') {
                  this.hospitalAllList = res.data.object;
                }
              });
              setTimeout(() => {
                _this.loading1 = false;
                _this.hospitalList = _this.hospitalAllList.filter(item => item.name.indexOf(query) > -1);
              }, 200);
            }
          }
        } else {
          if (type === 'pharmacy') {
            this.pharmacyListData = [];
          }
          if (type === 'hospital') {
            this.hospitalList = [];
          }
        }
      },
      handleSelect (item, type) {
        if (type === 'pharmacy') {
          this.formdata.pharmacyList = item;
        }
      }
    },
    created () {
      if (this.dialogData.info) {
        this.post(this.api.cooperationHospital.getHospitalPackageDetail, { id: this.dialogData.info }).then(res => {
          if (res.data.code === '200') {
            let resData = res.data.object
            let cloneData = JSON.parse(JSON.stringify(resData));
            this.formdata = cloneData;
            this.hospitalList = [{
              id: resData.hospitalId,
              name: resData.hospitalName,
            }]
            this.doctorLeader(resData.hospitalId);
            this.getDoctorStudio(resData.leaderId);
            this.getPackageTypeList(resData.hospitalId);

            this.formdata.pharmacyList = resData.pharmacyList.map(item => item.hospitalId);
            this.pharmacyListData = resData.pharmacyList.map(item => ({
              id: item.hospitalId,
              name: item.name
            }));
          }
        })
      }
    }
  }
</script>

<style>
</style>